#pragma once
#include "message.hpp"
#include <iostream>
#include <memory>
#include <time.h>
#include <vector>
#include <sstream>
#include <cassert>

/*
    %d 日期
    %T 缩进
    %t 线程id
    %p 日志级别
    %c 日志器名称
    %f 文件名
    %l 行号
    %m 日志消息
    %n 换行
*/
namespace log
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, const LogMsg &msg) = 0;
    };

    // 读取日志有效信息
    class MsgFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    // 读取日志等级
    class LevelFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << outLevel::toString(msg._level);
        }
    };

    // 读取日志器名称
    class NameFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._name;
        }
    };

    // 读取线程id
    class ThreadFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };

    // 读取时间
    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(std::string fmt = "%H:%M:%S") : _fmt(fmt) {} // 构造函数
        void format(std::ostream &out, const LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._time, &t);
            char timemsg[32];
            strftime(timemsg, 31, _fmt.c_str(), &t);
            out << timemsg;
        }

    private:
        std::string _fmt; // 用户自定义的时间格式显示
    };

    // 读取源文件名
    class FileFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    // 读取行号
    class LineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    // 读取\t
    class TabFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    // 读取\n
    class WrapFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    // 读取其他字符
    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(std::string othermsg = "") : _othermsg(othermsg) {}
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << _othermsg;
        }

    private:
        std::string _othermsg;
    };

    class Format
    {
    public:
        using ptr = std::shared_ptr<Format>;
        Format(const std::string &pattern = "[%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n") : _pattern(pattern)
        {
            assert(parsePattern());
        }

        std::ostream &format(std::ostream &out, const LogMsg &msg)
        {
            for (const auto &e : _formats)
            {
                e->format(out, msg);
            }
            return out;
        }

        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

    private:
        bool parsePattern()
        {
            int pos = 0;
            int n = _pattern.size();
            std::vector<std::pair<std::string, std::string>> v;
            std::string key, val;
            while (pos < n)
            {
                // 遇到原始字符
                if (_pattern[pos] != '%')
                {
                    val += _pattern[pos++];
                    continue;
                }
                // 遇到%%,算作一个原始字符%
                if (pos + 1 < n && _pattern[pos + 1] == '%')
                {
                    val += '%';
                    pos += 2;
                    continue;
                }
                if (!val.empty())
                {
                    v.push_back(std::make_pair("", val));
                    val.clear();
                }

                pos++; // 跳过百分号
                // 走到这表示%号是最后一个字符,后面没有内容了
                if (pos == n)
                {
                    std::cout << "%号没有匹配的格式化字符" << std::endl;
                    return false;
                }
                // 走到这表示遇到的是格式化字符
                key = _pattern[pos++];
                // 判断格式化字符后是否存在子格式化串
                if (pos < n && _pattern[pos] == '{')
                {
                    pos++;
                    while (pos < n && _pattern[pos] != '}')
                    {
                        val += _pattern[pos++];
                    }
                    if (pos == n)
                    {
                        std::cout << "子格式串{}匹配失败" << std::endl;
                        return false;
                    }
                    pos++;
                }
                v.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }

            for (const auto &e : v)
            {
                _formats.push_back(createItem(e.first, e.second));
            }

            return true;
        }

        // 根据格式创建格式化对象
        FormatItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return FormatItem::ptr(new TimeFormatItem(val));
            if (key == "T")
                return FormatItem::ptr(new TabFormatItem());
            if (key == "t")
                return FormatItem::ptr(new ThreadFormatItem());
            if (key == "p")
                return FormatItem::ptr(new LevelFormatItem());
            if (key == "c")
                return FormatItem::ptr(new NameFormatItem());
            if (key == "f")
                return FormatItem::ptr(new FileFormatItem());
            if (key == "l")
                return FormatItem::ptr(new LineFormatItem());
            if (key == "m")
                return FormatItem::ptr(new MsgFormatItem());
            if (key == "n")
                return FormatItem::ptr(new WrapFormatItem());
            if (key == "")
                return FormatItem::ptr(new OtherFormatItem(val));
            std::cout << "%后出现了无效的格式化字符" << std::endl;
            abort();
        }

        std::string _pattern;
        std::vector<FormatItem::ptr> _formats;
    };
};